#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''账户相关form验证'''

from django import forms
from django.forms import fields
from repository import models
from django.forms import ValidationError


class RegisterForm(forms.Form):
    '''用户注册form验证'''

    def __init__(self, request, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.request = request

    username = fields.CharField(error_messages={'required': '用户名不能为空'})
    email = fields.EmailField(error_messages={'required': '邮箱不能为空','invalid': '请输入有效邮箱'})
    password = fields.CharField(error_messages={'required': '密码不能为空'})
    password2 = fields.CharField(required=True)
    checkcode = fields.CharField(error_messages={'required': '请输入验证码'})

    def clean_username(self):
        '''验证用户名是否合法'''
        res = models.UserInfo.objects.filter(username=self.cleaned_data['username']).exists()
        if res:
            raise ValidationError('用户名已被注册')
        else:
            return self.cleaned_data['username']

    def clean_email(self):
        '''验证邮箱是否合法'''
        res = models.UserInfo.objects.filter(email=self.cleaned_data['email']).exists()
        if res:
            raise ValidationError('邮箱已被注册')
        else:
            return self.cleaned_data['email']

    def clean_checkcode(self):
        '''检查验证码'''
        if not self.request.session.get('checkcode'):
            raise ValidationError('验证码不正确')
        elif not self.cleaned_data['checkcode'].upper() == self.request.session.get('checkcode').upper():
            raise ValidationError('验证码不正确')
        else:
            return self.cleaned_data['checkcode']

    def clean(self):
        '''检查密码是否一致'''
        if not self.cleaned_data.get('password') == self.cleaned_data.get('password2'):
            raise ValidationError('密码不一致')
        else:
            return self.cleaned_data



class LoginForm(forms.Form):
    '''用户登录form验证'''

    def __init__(self, request, *args, **kwargs):
        super(LoginForm, self).__init__(*args, **kwargs)
        self.request = request

    username = fields.CharField(error_messages={'required': '请输入用户名'})
    password = fields.CharField(error_messages={'required': '请输入密码'})
    checkcode = fields.CharField(error_messages={'required': '请输入验证码'})

    def clean_checkcode(self):
        '''检查验证码'''
        if not self.request.session.get('checkcode'):
            raise ValidationError('验证码不正确')
        elif not self.cleaned_data['checkcode'].upper() == self.request.session.get('checkcode').upper():
            raise ValidationError('验证码不正确')
        else:
            return self.cleaned_data['checkcode']

    def clean(self):
        '''检查用户名和密码'''
        if self.cleaned_data.get('username') and self.cleaned_data.get('password'):
            user_obj = models.UserInfo.objects.filter(username=self.cleaned_data.get('username'),
                                                    password=self.cleaned_data.get('password')
                                                    ).first()
            if user_obj:
                self.request.session['nid'] = user_obj.nid
                self.request.session['is_login'] = True
                blog_obj =  models.Blog.objects.filter(user_id=user_obj.nid).first()
                if blog_obj:
                    self.request.session['blog_nid'] = blog_obj.nid
                return self.cleaned_data
            else:
                raise ValidationError('用户名或密码错误')
        else:
            return self.cleaned_data
